package com.example.wyh.intelcheckbash.task;

import android.app.ActionBar;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.HttpUtil;
import com.example.wyh.intelcheckbash.LocalStorage;
import com.example.wyh.intelcheckbash.MainActivity;
import com.example.wyh.intelcheckbash.R;
import com.example.wyh.intelcheckbash.SeismicActivity;
import com.example.wyh.intelcheckbash.StatisticalCheckActivity;
import com.example.wyh.intelcheckbash.bluetoothchat.BluetoothChatFragment;
import com.example.wyh.intelcheckbash.common.SysExitUtil;
import com.example.wyh.intelcheckbash.sqlite.TaskDbHelper;
import com.example.wyh.intelcheckbash.temptemperature.ThermometricActivity;
import com.google.zxing.activity.CaptureActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by chen on 17/11/4.
 */

public class CheckDefectActivity extends AppCompatActivity {
//    private ListView mCheckDefectListView;
//    private ArrayList<ListViewItem>  mViewItemsArraylists;
//    private ListViewAdapter adapter;
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_check_defect);
//        setTitle("异常点");
//
//    }


    private GroupListAdapter adapter = null;
    private ListView listView = null;
    JSONArray taskList;
    String taskXTM;
    public JSONArray defectInfos;
    JSONArray currentTaskCheckedInfo;
    Spinner taskSpinner;
    BluetoothChatFragment mFragment = MainActivity.getInstance();
    ArrayList taskNames;
    JSONArray needUpdateEqiupment = new JSONArray();
    String mYhxtm = "";
    String mDeviceToken ="";
    String mUserName = "";
    Integer mUploadCount = 0;

    public void getDefectData(int position) {
        taskList = getTaskList();
        taskXTM = getTaskXTM(position);
        currentTaskCheckedInfo = getTaskAllCheckedXM(taskXTM);

        defectInfos = getDefectByXtm();
        Log.e("defectInfos",defectInfos.toString());

    }
    public  void  initActionBar(){
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.actionbar_custom,new LinearLayout(CheckDefectActivity.this),false);
            android.support.v7.app.ActionBar.LayoutParams layout = new android.support.v7.app.ActionBar.LayoutParams(
                    android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT, android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT);
            actionBar.setCustomView(v, layout);
            Toolbar parent = (Toolbar) v.getParent();
            parent.setContentInsetsAbsolute(0, 0);
        }

        TextView actionBarTitle = (TextView) findViewById(R.id.action_bar_title);
        actionBarTitle.setText("异常点");

        ImageView title_logo = (ImageView)findViewById(R.id.title_logo_id);
        title_logo.setImageResource(R.drawable.check_static);

        RelativeLayout bar_back_btn =  (RelativeLayout) findViewById(R.id.bar_back_btn);
        bar_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                taskList = null;
                currentTaskCheckedInfo = null;
                defectInfos = null;
                needUpdateEqiupment = null;
                listView = null;
                taskSpinner = null;
                adapter = null;
                CheckDefectActivity.this.finish();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            taskList = null;
            currentTaskCheckedInfo = null;
            defectInfos = null;
            needUpdateEqiupment = null;
            listView = null;
            taskSpinner = null;
            adapter = null;
            this.finish();
        }
        return  true;
//        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_defect);
        SysExitUtil.activityList.add(CheckDefectActivity.this);
        initActionBar();
        getHttpHeads();
        taskList = getTaskList();
        taskNames = getTaskNames(taskList);
        taskSpinner = initTackSpinner("选择任务", R.id.select_task_defect, taskNames);
        initTaskChangeButton();
        initUpdataDefectAction();

    }

    public Spinner initTackSpinner(String title, int id, ArrayList spinnerData) {
        final Spinner spinner = (Spinner) findViewById(id);
        spinner.setPrompt(title);
        ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, spinnerData);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                spinner.setSelection(position);
                updateListView(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        return spinner;
    }
    public void checkCBxmInfoToCompleteInfo(EditText editText,int position, String checkCBinfo)
    {
        JSONObject xmInfo = new JSONObject();
        try {
            xmInfo = defectInfos.getJSONObject(position).getJSONArray("xmdata").getJSONObject(0);
        } catch (JSONException e) {
            e.printStackTrace();
        }


        try {
            xmInfo.put("cdjg", checkCBinfo);
            double test_value = Double.parseDouble(checkCBinfo);
            double sxz = Double.parseDouble(xmInfo.getString("sxz"));
            double xxz = Double.parseDouble(xmInfo.getString("xxz"));
            String sfycd = (test_value < xxz || test_value >sxz) ? "1":"0";
            xmInfo.put("sfycd",sfycd);
            defectInfos.getJSONObject(position).getJSONArray("xmdata").put(0, xmInfo);
            if (sfycd.equals("1"))
            {
                editText.setTextColor(Color.parseColor("#ff0000"));
            }
            else
            {
                editText.setTextColor(Color.parseColor("#000000"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void updateListView(final int position) {
        needUpdateEqiupment = new JSONArray();
        getDefectData(position);
        adapter = new GroupListAdapter(this, defectInfos);
        listView = (ListView) findViewById(R.id.show_check_defect_lsit_view);
        listView.setAdapter(adapter);

        Log.e("defectInfos",defectInfos.toString());
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                Intent intent = new Intent(CheckDefectActivity.this, CheckInfoActivity.class);
//                try {
//                    JSONObject info = defectInfos.getJSONObject(i);
//                    JSONObject checkDetail = getCheckDetail(info.getString("rwxtm"), info.getString("xdjqyxtm"), info.getString("qysbxtm"), info.getJSONArray("xmdata").getJSONObject(0).getString("xmxtm"));
//                    intent.putExtra("checkDetail", checkDetail.toString());
//                    intent.putExtra("xmInfo", info.getJSONArray("xmdata").getJSONObject(0).toString());
//                    intent.putExtra("checkOrigin",defectInfos.getJSONObject(i).getString("qyms"));
//                    intent.putExtra("equipment_code",defectInfos.getJSONObject(i).getJSONArray("xmdata").getJSONObject(0).getString("equipment_code"));
//                    startActivityForResult(intent, i);
//
//                } catch (Exception e) {
//                    Log.e("Exception========：", e.toString());
//                }

            }
        });
    }


    private static class GroupListAdapter extends BaseAdapter {

        private JSONArray listTag = null;
        private LayoutInflater mLayoutInflater;
//        ListViewAdapter.ViewHolderfirstType viewHolderfirstType = null;
//        ListViewAdapter.ViewHoldersecondType viewHoldersecondType = null;

        TextView check_title_text_view;
        TextView check_standard_text_view;
        Button test_seismic_btn;
        TextView check_danwei_text_view;
//        CheckBox checkFaceBugId;
        EditText show_seismic_id_view;
        CheckBox checkBoxPass;
        CheckBox checkBoxDisPass;
        Context mContext;


        public GroupListAdapter(Context context, JSONArray listTag) {
//            super(context, 0, objects);
            this.listTag = listTag;
            mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mContext = context;
        }

        @Override
        public boolean isEnabled(int position) {
            try {
                if (listTag.getJSONObject(position).getString("TYPE").equals("Tag")) {
                    return false;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return super.isEnabled(position);
        }

        @Override
        public int getCount() {
            return listTag.length();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = convertView;
            final int mPosition = position;

            int Type = getType(position);

            switch (Type) {
                case 0:
                    view = mLayoutInflater.inflate(R.layout.xm_defect_item, null);
                    TextView group_list_item_text = (TextView) view.findViewById(R.id.group_list_item_text);
                    try {
                        JSONObject equipment = listTag.getJSONObject(position);
                        group_list_item_text.setText(equipment.getString("name"));
                    } catch (JSONException e) {
                        Log.e("========JSONException==", e.toString());
                        e.printStackTrace();
                    }
                    break;
                case 1:
                    view = mLayoutInflater.inflate(R.layout.list_item_ganguan, null);
                    check_title_text_view = (TextView) view.findViewById(R.id.check_title_gangan);
                    check_standard_text_view = (TextView) view.findViewById(R.id.check_standard_gangan_id);
                    checkBoxPass = (CheckBox) view.findViewById(R.id.pass_id);
                    checkBoxDisPass = (CheckBox) view.findViewById(R.id.dispass_id);
                    check_title_text_view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            CheckDefectActivity task_activity = (CheckDefectActivity) mContext;
                            task_activity.jumpToCheckInfoActivity(mPosition);
                        }
                    });
//                    checkFaceBugId = (CheckBox) view.findViewById(R.id.face_bug_id);
                    try {
                        JSONObject equipment = listTag.getJSONObject(position);
//                        Log.e("========equipment"+ position,equipment.toString() );
                        JSONObject xmInfo = equipment.getJSONArray("xmdata").getJSONObject(0);
//                        Log.e("========xmInfo"+ position,xmInfo.toString() );
                        check_title_text_view.setText(xmInfo.getString("xmms"));
                        check_standard_text_view.setText(equipment.getString("djbz"));

                        CheckDefectActivity task_activity = (CheckDefectActivity) mContext;
                        JSONObject info = task_activity.defectInfos.getJSONObject(position);
                        JSONObject checkDetail = task_activity.getCheckDetail(info.getString("rwxtm"), info.getString("xdjqyxtm"), info.getString("qysbxtm"), info.getJSONArray("xmdata").getJSONObject(0).getString("xmxtm"));
//                        Log.e("checkDetail",checkDetail.toString());
                        JSONArray cdjgzlb = checkDetail.getJSONArray("cdjgzlb");
//                        Log.e("checkDetailcdjgzlb",cdjgzlb.toString());
                        String correctValue = cdjgzlb.getJSONObject(0).getString("sfyc").equals("0")?cdjgzlb.getJSONObject(0).getString("z") : cdjgzlb.getJSONObject(1).getString("z");
                        String errorValue = cdjgzlb.getJSONObject(0).getString("sfyc").equals("1")?cdjgzlb.getJSONObject(0).getString("z") : cdjgzlb.getJSONObject(1).getString("z");
                        checkBoxPass.setText(correctValue);
                        checkBoxDisPass.setText(errorValue);
                        initCheckBoxAction(checkBoxPass, position, "pass",correctValue,errorValue);
                        initCheckBoxAction(checkBoxDisPass, position, "dispass",correctValue,errorValue);

                        try {
                            if (xmInfo.getString("cdjg").equals(correctValue)) {
                                checkBoxPass.setChecked(true);
                            }
                        } catch (JSONException e) {

                        }
                        try {
                            if (xmInfo.getString("cdjg").equals(errorValue)) {

                                checkBoxDisPass.setChecked(true);
                            }
                        } catch (JSONException e) {

                        }


                    } catch (Exception e) {

                    }
                    //如果要复用，不同于一种样式的listView ,这样的写法是错误的,具体原因看下面第一个小哥评论的说法
//                    convertView.setTag(R.id.viewHolderGanguanType, viewHolderfirstType);
                    break;
                case 2:
                    view = mLayoutInflater.inflate(R.layout.list_item_celiang, null);
                    check_title_text_view = (TextView) view.findViewById(R.id.check_celiang_title);
                    check_standard_text_view = (TextView) view.findViewById(R.id.check_celiang_standard_id);
                    test_seismic_btn = (Button) view.findViewById(R.id.test_seismic_btn_id);
                    check_danwei_text_view = (TextView) view.findViewById(R.id.celiang_danwei);
//                    checkFaceBugId = (CheckBox) view.findViewById(R.id.seismic_bug_check);
                    show_seismic_id_view = (EditText) view.findViewById(R.id.show_seismic_id);
                    check_title_text_view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            CheckDefectActivity task_activity = (CheckDefectActivity) mContext;
                            task_activity.jumpToCheckInfoActivity(mPosition);
                        }
                    });

                    try {
                        JSONObject equipment = listTag.getJSONObject(position);
                        JSONObject xmInfo = equipment.getJSONArray("xmdata").getJSONObject(0);
                        check_title_text_view.setText(xmInfo.getString("xmms"));
                        check_standard_text_view.setText(equipment.getString("djbz"));

                        CheckDefectActivity task_activity = (CheckDefectActivity) mContext;
                        JSONObject info = task_activity.defectInfos.getJSONObject(position);
                        JSONObject checkDetail = task_activity.getCheckDetail(info.getString("rwxtm"), info.getString("xdjqyxtm"), info.getString("qysbxtm"), info.getJSONArray("xmdata").getJSONObject(0).getString("xmxtm"));
                        String cddw = checkDetail.getString("cddw");
                        if (cddw.equals("C")) {
                            cddw = " ℃";
                        }
                        check_danwei_text_view.setText(cddw);
//                        if (equipment.getString("cdlx").equals("CW")) {
//                            check_danwei_text_view.setText(" ℃");
//                        }

                        try {
                            show_seismic_id_view.setText(xmInfo.getString("cdjg"));
                        } catch (JSONException e) {

                        }


                    } catch (JSONException e) {

                    }
                    test_seismic_btn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String test_type_info = "";
                            try {
                                test_type_info = listTag.getJSONObject(mPosition).getString("cdlx");
                            } catch (JSONException e) {

                            }
                            if (test_type_info.equals("CW")) {
                                CheckDefectActivity task_activity = (CheckDefectActivity) mContext;
                                task_activity.jumpToTestThermom(mPosition);
                            } else if (test_type_info.equals("CZ")) {
                                CheckDefectActivity task_activity = (CheckDefectActivity) mContext;
                                task_activity.jumpToTestSeismic(mPosition);
                            } else {
                                Log.e("type", "test_type_info:" + test_type_info);
                            }
                        }
                    });
//                  convertView.setTag(viewHolderfirstType);  //如果要复用，不同于一种样式的listView ,这样的写法是错误的,具体原因看下面第一个小哥评论的说法
//                    convertView.setTag(R.id.viewHolderCeliangType, viewHoldersecondType);
                    break;
                case 3:
                    view = mLayoutInflater.inflate(R.layout.chaobiao_item, null);
                    check_title_text_view = (TextView) view.findViewById(R.id.check_chaobiao_title);
                    check_standard_text_view = (TextView) view.findViewById(R.id.check_chaobiao_standard_id);
                    check_danwei_text_view = (TextView) view.findViewById(R.id.chaobiao_danwei);
//                    checkFaceBugId = (CheckBox) view.findViewById(R.id.seismic_bug_check);
                    show_seismic_id_view = (EditText) view.findViewById(R.id.show_chaobiao_text_id);
                    check_title_text_view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            CheckDefectActivity task_activity = (CheckDefectActivity) mContext;
                            task_activity.jumpToCheckInfoActivity(mPosition);
                        }
                    });
                    try {
                        JSONObject equipment = listTag.getJSONObject(position);
                        JSONObject xmInfo = equipment.getJSONArray("xmdata").getJSONObject(0);
                        check_title_text_view.setText(xmInfo.getString("xmms"));
                        check_standard_text_view.setText(equipment.getString("djbz"));

                        CheckDefectActivity task_activity = (CheckDefectActivity) mContext;
                        JSONObject info = task_activity.defectInfos.getJSONObject(position);
                        JSONObject checkDetail = task_activity.getCheckDetail(info.getString("rwxtm"), info.getString("xdjqyxtm"), info.getString("qysbxtm"), info.getJSONArray("xmdata").getJSONObject(0).getString("xmxtm"));
                        String cddw = checkDetail.getString("cddw");
                        if (cddw.equals("C")) {
                            cddw = " ℃";
                        }
                        check_danwei_text_view.setText(cddw);
                        try {
                            show_seismic_id_view.setText(xmInfo.getString("cdjg"));
                            if (xmInfo.getString("sfycd").equals("1"))
                            {
                                show_seismic_id_view.setTextColor(Color.parseColor("#ff0000"));
                            }
                        } catch (JSONException e) {

                        }
                        show_seismic_id_view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                            @Override
                            public void onFocusChange(View v, boolean hasFocus) {
                                if (!hasFocus) {
                                    // 判 断items的长度是否大于0，可以防止数组越界
                                    EditText editText = (EditText)v;
                                    if (editText.getText().toString().length() > 0)
                                    {
                                        CheckDefectActivity task_activity = (CheckDefectActivity) mContext;
                                        task_activity.checkCBxmInfoToCompleteInfo(editText,mPosition,editText.getText().toString());
                                    }
                                }
                            }
                        });

                    } catch (JSONException e) {

                    }
                    break;
            }

            return view;
        }
// 正则表达式
//        String  regEx  =  "^([0-9]{1,10}+(.[0-9]{1,5})?)$";
//        Pattern p   =   Pattern.compile(regEx);
//        String cdjg = listTag.getJSONObject(position).getJSONArray("xmdata").getJSONObject(0).getString("cdjg");
//        Matcher m = p.matcher(cdjg);
//                if (m.matches() == true)
//                        return 2;
        public Integer getType(int position) {
            try {
                if (listTag.getJSONObject(position).getString("TYPE").equals("Tag")) {
                    return 0;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                if (listTag.getJSONObject(position).getString("cdlx").equals("CW")||
                        listTag.getJSONObject(position).getString("cdlx").equals("CZ"))
                {
                    return 2;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                if (listTag.getJSONObject(position).getString("cdlx").equals("CB"))
                {
                    return 3;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return 1;
        }

        public void initCheckBoxAction(final CheckBox checkBox, final int position, final String key, final String correctValue, final String errorValue) {
            checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    CheckDefectActivity checkDefectActivity = (CheckDefectActivity) mContext;
                    checkDefectActivity.setCheckboxChanged(position, checkBox.isChecked(), key,correctValue,errorValue);
                }
            });
        }


    }

    public void setCheckboxChanged(int position, boolean isChecked, String key ,final String correctValue, final String errorValue) {
        Log.e("isChecked",isChecked+"key"+key);
        JSONObject xmInfo = new JSONObject();
        View itemView = listView.getChildAt(position - listView.getFirstVisiblePosition());
        try {
            xmInfo = defectInfos.getJSONObject(position).getJSONArray("xmdata").getJSONObject(0);
        } catch (JSONException e) {

            e.printStackTrace();
        }
        CheckBox passCheck = (CheckBox) itemView.findViewById(R.id.pass_id);
        CheckBox dispassCheck = (CheckBox) itemView.findViewById(R.id.dispass_id);
        if (key.equals("dispass")) {
            dispassCheck.setChecked(isChecked);
            passCheck.setChecked(!isChecked);
            try {
                xmInfo.put("cdjg", isChecked ? errorValue : correctValue);
                xmInfo.put("sfycd",isChecked ? "1" : "0");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (key.equals("pass")) {
            passCheck.setChecked(isChecked);
            dispassCheck.setChecked(!isChecked);
            try {
                xmInfo.put("cdjg", isChecked ? correctValue : errorValue);
                xmInfo.put("sfycd",isChecked ? "0" : "1");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
//        if (key.equals("faceBug")) {
//            try {
//                xmInfo.put("sfycd", isChecked ? "1" : "0");
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//        }
        try {
            defectInfos.getJSONObject(position).getJSONArray("xmdata").put(0, xmInfo);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    public JSONArray getDefectByXtm() {
        JSONArray recode = new JSONArray();
        for (int i = 0; i < currentTaskCheckedInfo.length(); i++) {
            JSONArray xmInfos = new JSONArray();
            try {
                xmInfos = currentTaskCheckedInfo.getJSONObject(i).getJSONObject("data").getJSONArray("xmdata");
                JSONArray types = currentTaskCheckedInfo.getJSONObject(i).getJSONArray("task_info_type");
                for (int j = 0; j < xmInfos.length(); j ++)
                {
                    xmInfos.getJSONObject(j).put("cdlx",types.getJSONObject(j).getString("cdlx"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                JSONObject eq = currentTaskCheckedInfo.getJSONObject(i).getJSONObject("data");
                JSONArray equipmentXMSInfo = new JSONArray();
                JSONObject info = new JSONObject();
                info.put("TYPE", "Tag");
                info.put("name", eq.getString("sbms"));
                equipmentXMSInfo.put(info);


                for (int j = 0; j < xmInfos.length(); j++) {
                    try {
                        if (xmInfos.getJSONObject(j).getString("sfycd").equals("1")) {
                            JSONArray xmData = new JSONArray();
                            JSONObject equipment = initEquipment(eq);
                            xmData.put(xmInfos.getJSONObject(j));
                            JSONObject checkDetail = getCheckDetail(equipment.getString("rwxtm"), equipment.getString("xdjqyxtm"), equipment.getString("qysbxtm"), xmInfos.getJSONObject(j).getString("xmxtm"));
                            String standard = checkDetail.getString("djbz");
                            equipment.put("xmdata", xmData);
                            equipment.put("djbz", standard);
                            equipment.put("cdlx", checkDetail.getString("cdlx"));
                            equipmentXMSInfo.put(equipment);
//                            Log.e("========xmdata=",xmInfos.getJSONObject(j).toString());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (equipmentXMSInfo.length() > 1) {
                    for (int k = 0; k < equipmentXMSInfo.length(); k++) {
                        recode.put(equipmentXMSInfo.getJSONObject(k));
                    }
                    needUpdateEqiupment.put(eq);

                }


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return recode;
    }

    public JSONObject getCheckDetail(String taskXTM, String areaXTM, String equipmentXTM, String xmXTM) {
        JSONObject checkDetail = new JSONObject();
        for (int i = 0; i < taskList.length(); i++) {
            try {

                boolean status = taskList.getJSONObject(i).getString("xtm").equals(taskXTM);
                if (status) {
                    JSONArray areaInfo = taskList.getJSONObject(i).getJSONArray("data");

                    for (int j = 0; j < areaInfo.length(); j++) {
                        boolean areaInfoStatus = areaInfo.getJSONObject(j).getString("xtm").equals(areaXTM);

                        if (areaInfoStatus) {

                            JSONArray equipmentsInfo = areaInfo.getJSONObject(j).getJSONArray("data");
                            for (int m = 0; m < equipmentsInfo.length(); m++) {

                                boolean equipmentsInfoStatus = equipmentsInfo.getJSONObject(m).getString("xtm").equals(equipmentXTM);

                                if (equipmentsInfoStatus) {

                                    JSONArray xmInfos = equipmentsInfo.getJSONObject(m).getJSONArray("data");
                                    for (int n = 0; n < xmInfos.length(); n++) {

                                        boolean xmStatus = xmInfos.getJSONObject(n).getString("xtm").equals(xmXTM);
                                        if (xmStatus) {
                                            checkDetail = xmInfos.getJSONObject(n);
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                            break;
                        }

                    }
                    break;
                }
            } catch (JSONException e) {
                Log.e("=====JSONException====", e.toString());
                e.printStackTrace();
            }
        }
        return checkDetail;
    }

    public JSONObject initEquipment(JSONObject mCurrentEquipment) {
        JSONObject uploadEquipmentData = new JSONObject();
        try {
            uploadEquipmentData.put("sbms", mCurrentEquipment.getString("sbms"));
            uploadEquipmentData.put("qysbxtm", mCurrentEquipment.getString("qysbxtm")); //shebi id
            uploadEquipmentData.put("sbzt", mCurrentEquipment.getString("sbzt"));
            uploadEquipmentData.put("rwms", mCurrentEquipment.getString("rwms"));
            uploadEquipmentData.put("rwxtm", mCurrentEquipment.getString("rwxtm")); //renwu id
            uploadEquipmentData.put("qyms", mCurrentEquipment.getString("qyms"));
            uploadEquipmentData.put("xdjqyxtm", mCurrentEquipment.getString("xdjqyxtm")); //quyu id
            uploadEquipmentData.put("smqyms", mCurrentEquipment.getString("smqyms"));
            uploadEquipmentData.put("smsj", mCurrentEquipment.getString("smsj"));
            uploadEquipmentData.put("date", mCurrentEquipment.getString("date"));
            uploadEquipmentData.put("xjr", mCurrentEquipment.getString("xjr"));

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return uploadEquipmentData;


    }

    public JSONArray getTaskAllCheckedXM(String taskXTM) {
        JSONArray completeXmInfo = new JSONArray();
        TaskDbHelper taskDbHelper = new TaskDbHelper(CheckDefectActivity.this);
        SQLiteDatabase db = taskDbHelper.getReadableDatabase();
//        String query = "time = '" + HttpUtil.getCurrentDateString() +
//                "' and user_id = '" + LocalStorage.getUserXtm(CheckDefectActivity.this)
//                + "'" + " and task_id = '" + taskXTM + "'" ;
        String query = "user_id = '" + LocalStorage.getUserXtm(CheckDefectActivity.this)
                + "'" + " and task_id = '" + taskXTM + "'" ;
        String[] columns = {"data","task_info_type"};
        Cursor cursor = null;
        try {
            cursor = db.query("complete_task", columns, query, null, null, null, null);

            while (cursor.moveToNext()) {
                if (cursor.getColumnIndex("data") > -1) {
                    String data = cursor.getString(cursor.getColumnIndex("data"));
                    String task_info_type = cursor.getString(cursor.getColumnIndex("task_info_type"));
                    try {
                        JSONObject completeInfo = new JSONObject();
                        completeInfo.put("data",new JSONObject(data));
                        completeInfo.put("task_info_type",new JSONArray(task_info_type));
                        Log.e("==========completeInfo",completeInfo.toString());
                        completeXmInfo.put(completeInfo);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

            }

        } catch (SQLException e) {
        }
        //关闭数据库
        db.close();
        return completeXmInfo;
    }

    public String getTaskXTM(int i) {
        String xtm = "";
        try {
            xtm = taskList.getJSONObject(i).getString("xtm");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return xtm;
    }



    public JSONArray getTaskList() {

        JSONArray mAllTaskList =  new JSONArray();
        mAllTaskList = getTaskListTest("后夜班",mAllTaskList);
        mAllTaskList = getTaskListTest("白班",mAllTaskList);
        mAllTaskList = getTaskListTest("前夜班",mAllTaskList);
        mAllTaskList = getTaskListTest("燃料夜班",mAllTaskList);
        mAllTaskList = getTaskListTest("燃料白班",mAllTaskList);
        return mAllTaskList;
    }

    public  JSONArray getTaskListTest(String bc, JSONArray taskList){
        TaskDbHelper taskDbHelper = new TaskDbHelper(CheckDefectActivity.this);
        SQLiteDatabase db =  taskDbHelper.getReadableDatabase();
//        String query =  "time = '"+ HttpUtil.getCurrentDateString()+
//                "' and user_id = '" + LocalStorage.getUserXtm(CheckDefectActivity.this)
//                + "'"  + " and bc = '" + bc + "'" ;
        String query =  "start_date <= '" + HttpUtil.getCurrentDateString() +
                "' and end_date >= '"  + HttpUtil.getCurrentDateString() +
                "' and user_id = '" + LocalStorage.getUserXtm(CheckDefectActivity.this)
                + "'"  + " and bc = '" + bc + "'" ;

        String[] columns = {"data"};
        Cursor cursor = null;
        try {
            cursor = db.query("task", columns, query, null, null, null, null);
            while (cursor.moveToNext()){

                JSONObject task = new  JSONObject();
                if(cursor.getColumnIndex("data")>-1){
                    String data =  cursor.getString(cursor.getColumnIndex("data"));
                    try {
                        task =  new JSONObject(data);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                taskList.put(task);
            }
        } catch (SQLException e) {
        }
        //关闭数据库
        db.close();

        return taskList;
    }



    public ArrayList<String> getTaskNames(JSONArray temp) {
        ArrayList<String> names = new ArrayList<String>();
        try {
            for (int j = 0; j < temp.length(); j++) {
                names.add(temp.getJSONObject(j).getString("description"));
            }
            return names;

        } catch (Exception e) {

        }

        return names;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        final Intent resultData = data;
        //扫描二维码

        if (resultCode == 1001) {
            try {
                String defectInfo = data.getStringExtra("defectInfo");
                updateDefactBug(requestCode, new JSONObject(defectInfo));
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else if (resultCode == 1002 || resultCode == 1003) {
            String mTestValue = resultData.getStringExtra("testValue");
            View itemView = listView.getChildAt(requestCode - listView.getFirstVisiblePosition());
            EditText test_result = (EditText) itemView.findViewById(R.id.show_seismic_id);
            test_result.setText(mTestValue);
            updateCheckValue(requestCode, mTestValue);
        }
    }

    public void bluetoothConnectSuccessJumpToTestThermom(final int position)
    {
        final Handler handler = new Handler(Looper.getMainLooper());
        final Runnable runnable = new Runnable(){
            @Override
            public void run() {
                startActivityForResult(new Intent(CheckDefectActivity.this, ThermometricActivity.class), position);
            }
        };
        handler.postDelayed(runnable,1000);

    }

    public void jumpToTestThermom(int position) {
        if (mFragment.mIsConnectedBlueTooth == false) {
            try {
                String bluetoothAddress = LocalStorage.getString(CheckDefectActivity.this,"blueToothAddress");
                if (bluetoothAddress.length() != 0)
                {
                    mFragment.setContext(CheckDefectActivity.this);
                    mFragment.position = position;
                    mFragment.setTestType("CheckDefectActivityTestThermom");
                    mFragment.connectDeviceWithAddress(bluetoothAddress);
                    MainActivity.setIsConnectedInFail(false);
                }
            }catch (Exception e)
            {
                Log.e("TaskCheckActivity == bluetooth",e.getMessage());
            }
        }
        else
        {
            startActivityForResult(new Intent(CheckDefectActivity.this, ThermometricActivity.class), position);
        }
    }
    public void jumpToCheckInfoActivity(int position)
    {
        Intent intent = new Intent(CheckDefectActivity.this, CheckInfoActivity.class);
        try {
            JSONObject info = defectInfos.getJSONObject(position);
            JSONObject checkDetail = getCheckDetail(info.getString("rwxtm"), info.getString("xdjqyxtm"), info.getString("qysbxtm"), info.getJSONArray("xmdata").getJSONObject(0).getString("xmxtm"));
            intent.putExtra("checkDetail", checkDetail.toString());
            intent.putExtra("xmInfo", info.getJSONArray("xmdata").getJSONObject(0).toString());
            intent.putExtra("checkOrigin",defectInfos.getJSONObject(position).getString("qyms"));
            intent.putExtra("equipment_code",defectInfos.getJSONObject(position).getJSONArray("xmdata").getJSONObject(0).getString("equipment_code"));
            startActivityForResult(intent, position);
        } catch (Exception e) {
            Log.e("Exception========：", e.toString());
        }
    }
    public void bluetoothConnectSuccessJumpToTestSeismic(final int position)
    {
        final Handler handler = new Handler(Looper.getMainLooper());
        final Runnable runnable = new Runnable(){
            @Override
            public void run() {
                startActivityForResult(new Intent(CheckDefectActivity.this, SeismicActivity.class), position);
            }
        };
        handler.postDelayed(runnable,1000);
    }

    public void jumpToTestSeismic(int position) {
        if (mFragment.mIsConnectedBlueTooth == false) {
            try {
                String bluetoothAddress = LocalStorage.getString(CheckDefectActivity.this,"blueToothAddress");
                if (bluetoothAddress.length() != 0)
                {
                    mFragment.setContext(CheckDefectActivity.this);
                    mFragment.position = position;
                    mFragment.setTestType("CheckDefectActivityTestSeismic");
                    mFragment.connectDeviceWithAddress(bluetoothAddress);
                    MainActivity.setIsConnectedInFail(false);
                }
            }catch (Exception e)
            {
                Log.e("TaskCheckActivity == bluetooth",e.getMessage());
            }
        }else
        {
            startActivityForResult(new Intent(CheckDefectActivity.this, SeismicActivity.class), position);
        }
    }

    public void initTaskChangeButton() {
        Button mPreTaskButton = (Button) findViewById(R.id.preBtnTaskDefect);
        mPreTaskButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = taskSpinner.getSelectedItemPosition();
                if (position > 0) {
                    taskSpinner.setSelection(position - 1);

                } else {
                    Toast.makeText(CheckDefectActivity.this, "已经是第一个任务了", Toast.LENGTH_SHORT).show();
                }

            }
        });

        Button mNextTaskButton = (Button) findViewById(R.id.nextBtnTaskDefect);
        mNextTaskButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = taskSpinner.getSelectedItemPosition();
                if (position < taskNames.size() - 1) {
                    taskSpinner.setSelection(position + 1);

                } else {
                    Toast.makeText(CheckDefectActivity.this, "已经是最后一个任务了", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void updateDefactBug(int position, JSONObject defectInfo) {
        JSONObject xmInfo = new JSONObject();
        try {
            xmInfo = defectInfos.getJSONObject(position).getJSONArray("xmdata").getJSONObject(0);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            xmInfo.put("lxzy", defectInfo.getString("lxzy"));
            xmInfo.put("lxr", defectInfo.getString("lxr"));
            xmInfo.put("qxdj", defectInfo.getString("qxdj"));
            xmInfo.put("qxms", defectInfo.getString("qxms"));
            xmInfo.put("jz",defectInfo.getString("jz"));
//            xmInfo.put("sfycd",defectInfo.getString("sfycd"));
            xmInfo.put("isqx",defectInfo.getString("isqx"));
            xmInfo.put("equipment_code",defectInfo.getString("equipment_code"));
            xmInfo.put("sbxt",defectInfo.getString("sbxt"));
            defectInfos.getJSONObject(position).getJSONArray("xmdata").put(0, xmInfo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public void updateCheckValue(int position, String value) {
        JSONObject xmInfo = new JSONObject();
        try {
            xmInfo = defectInfos.getJSONObject(position).getJSONArray("xmdata").getJSONObject(0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            xmInfo.put("cdjg", value);
            double test_value = Double.parseDouble(value);
            double sxz = Double.parseDouble(xmInfo.getString("sxz"));
            double xxz = Double.parseDouble(xmInfo.getString("xxz"));
            String sfycd = (test_value < xxz || test_value >sxz) ? "1":"0";
            xmInfo.put("sfycd",sfycd);
            defectInfos.getJSONObject(position).getJSONArray("xmdata").put(0, xmInfo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
//    public void updateCheckValue1(int position, String value) {
//
//        JSONObject xmInfo;
//        try {
//            xmInfo = mCurrentCompleteEquipmentInfo.getJSONArray("xmdata").getJSONObject(position);
//
//        } catch (JSONException e) {
//            xmInfo = initXMInfo(position);
//            e.printStackTrace();
//        }
//        try {
//            xmInfo.put("cdjg", value);
//            double test_value = Double.parseDouble(value);
//            JSONObject standard_xminfo = mCurrentEquipment.getJSONArray("data").getJSONObject(position);
//            double sxz = Double.parseDouble(standard_xminfo.getString("sxz"));
//            double xxz = Double.parseDouble(standard_xminfo.getString("xxz"));
//            String sfycd = (test_value < xxz || test_value >sxz) ? "1":"0";
//            xmInfo.put("sfycd",sfycd);
//            mCurrentCompleteEquipmentInfo.getJSONArray("xmdata").put(position, xmInfo);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//    }

    public void handleNeedUpdateEuipment() {

        for (int i = 0; i < defectInfos.length(); i++) {
            try {
                defectInfos.getJSONObject(i).getString("TYPE");
            } catch (JSONException e) {
                try {
                    JSONObject defectInfo = defectInfos.getJSONObject(i);
                    for (int j = 0; j < needUpdateEqiupment.length(); j++) {
                        JSONObject equipmentInfo = needUpdateEqiupment.getJSONObject(j);
                        boolean isTask = equipmentInfo.getString("rwxtm").equals(defectInfo.getString("rwxtm"));
                        boolean isArea = equipmentInfo.getString("xdjqyxtm").equals(defectInfo.getString("xdjqyxtm"));
                        boolean isEquipment = equipmentInfo.getString("qysbxtm").equals(defectInfo.getString("qysbxtm"));
                        JSONArray xmInfos = equipmentInfo.getJSONArray("xmdata");
                        if (isTask && isArea && isEquipment) {
                            for(int m =0 ;m<xmInfos.length();m++){
                                JSONObject newXmInfo = defectInfo.getJSONArray("xmdata").getJSONObject(0);
                                if(xmInfos.getJSONObject(m).getString("xtm").equals(newXmInfo.getString("xtm"))){
                                    xmInfos.put(m, newXmInfo);
                                    break;
                                }
                            }
                            break;
                        }

                    }

                } catch (JSONException e1) {

                    e1.printStackTrace();
                }

                e.printStackTrace();
            }
        }
    }

    public void initUpdataDefectAction(){
        Button updata_defect_btn = (Button) findViewById(R.id.updata_defect_btn);
        updata_defect_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handleNeedUpdateEuipment();
                try {
                    JSONObject eqiupment = needUpdateEqiupment.getJSONObject(0);
                    JSONArray xmdata = eqiupment.getJSONArray("xmdata");
                    for (int i = 0; i < xmdata.length(); i++) {
                        JSONObject xmInfo;
                        try {
                            xmInfo = xmdata.getJSONObject(i);
                        }catch (JSONException e)
                        {
                            continue;
                        }
                        try{
                            if (!xmInfo.getString("sfycd").equals("1")) {
                                xmdata.put(i, getNewXMInfo(xmInfo));
                            }
                        }catch (JSONException e){
                            xmdata.put(i, getNewXMInfo(xmInfo));
                        }
                    }
                    mUploadCount = 0;
                    eqiupment.put("isUploadSuccess","0");
                    saveCompleteCheckInLocal(eqiupment);
                    Log.e("eqiupment",eqiupment.toString());
                    try{
                        HttpUtil.requestNetForPostUploadAllData(mYhxtm, mDeviceToken, eqiupment, CheckDefectActivity.this,"CheckDefectActivity");
                    }catch (Exception e){

                    }
                } catch (Exception e) {
                }
            }
        });
    }




    public void saveCompleteCheckInLocal(JSONObject uploadEquipmentData) {
        TaskDbHelper taskDbHelper = new TaskDbHelper(CheckDefectActivity.this);
        SQLiteDatabase db = taskDbHelper.getWritableDatabase();
        String isUploadSuccess = null;
        String equipmentStatus = null;
        String equipment_id = null;
        try {
            isUploadSuccess = uploadEquipmentData.getString("isUploadSuccess");
            equipmentStatus = uploadEquipmentData.getString("sbzt");
            equipment_id = uploadEquipmentData.getString("qysbxtm");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ContentValues cv = new ContentValues();
        cv.put("isUploadSuccess",isUploadSuccess);
        cv.put("data",uploadEquipmentData.toString());
        int success = db.update("complete_task",cv,"equipment_id=? and equipmentStatus=? and user_id=? and time=?",new String[]{String.valueOf(equipment_id),
                String.valueOf(equipmentStatus),String.valueOf(LocalStorage.getUserXtm(CheckDefectActivity.this)),String.valueOf(HttpUtil.getCurrentDateString())});
        Log.e("success",success+"");
        db.close();

    }

    public JSONArray updateCompleteCheckTask(JSONArray todayCheckTask, JSONObject uploadEquipmentData) {
        boolean status = false;
        for (int i = 0; i < todayCheckTask.length(); i++) {
            try {
                String qysbxtm = todayCheckTask.getJSONObject(i).getString("qysbxtm");
                String rwxtm = todayCheckTask.getJSONObject(i).getString("rwxtm");
                String xdjqyxtm = todayCheckTask.getJSONObject(i).getString("xdjqyxtm");
                if (qysbxtm.equals(uploadEquipmentData.getString("qysbxtm")) && rwxtm.equals(uploadEquipmentData.getString("rwxtm")) && xdjqyxtm.equals(uploadEquipmentData.getString("xdjqyxtm"))) {
                    todayCheckTask.put(i, uploadEquipmentData);
                    status = true;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (!status) {
            todayCheckTask.put(uploadEquipmentData);
        }
        return todayCheckTask;

    }

    public  JSONObject getNewXMInfo(JSONObject xmInfo){
        JSONObject newXMInfo = new JSONObject();
        try {
            newXMInfo.put("pk",xmInfo.getString("pk"));
            newXMInfo.put("cdjg", xmInfo.getString("cdjg"));
            newXMInfo.put("xmxtm", xmInfo.getString("xmxtm"));
            newXMInfo.put("xmms", xmInfo.getString("xmms"));
            newXMInfo.put("sfgld", xmInfo.getString("sfgld"));
            newXMInfo.put("sfycd", xmInfo.getString("sfycd"));

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return  newXMInfo;

    }
    public  void  getHttpHeads(){
        TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
        mDeviceToken = TelephonyMgr.getDeviceId();
        JSONObject User =  LocalStorage.getObject(CheckDefectActivity.this, "User");
        mYhxtm = "";
        try {
            mYhxtm = User.getString("yhxtm");
            mUserName = User.getString("usernamecn");
        }catch (JSONException e)
        {
            throw new RuntimeException(e);
        }
    }

    public void updateProgressBar()
    {
        final Handler mainHander = new Handler(Looper.getMainLooper());
        mainHander.post(new Runnable() {
            @Override
            public void run() {
                JSONObject eqiupment = null;
                try {
                    eqiupment = needUpdateEqiupment.getJSONObject(mUploadCount);
                    eqiupment.put("isUploadSuccess","1");
                    saveCompleteCheckInLocal(eqiupment);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mUploadCount ++ ;
                if(mUploadCount < needUpdateEqiupment.length()){
                    try {
                        eqiupment = needUpdateEqiupment.getJSONObject(mUploadCount);
                        HttpUtil.requestNetForPostUploadAllData(mYhxtm, mDeviceToken, eqiupment, CheckDefectActivity.this,"CheckDefectActivity");
                    } catch (JSONException e) {
                    }
                }
                else if (mUploadCount == needUpdateEqiupment.length())
                {
                    Toast.makeText(CheckDefectActivity.this,"更新成功",Toast.LENGTH_SHORT).show();
                }

            }
        });

    }



}
